<!--  -->
<template>
  <div class="publish-container">
    <el-card>
      <div slot="header">
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>发布文章</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- 表单 -->
      <el-form
        :model="article"
        :rules="rules"
        ref="ruleForm"
        label-width="70px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="标题"
          prop="title"
        >
          <el-input v-model="article.title"></el-input>
        </el-form-item>
        <el-form-item
          label="内容"
          prop="content"
        >
          <!-- 富文本编辑器 -->
          <el-tiptap
            v-model="article.content"
            :extensions="extensions"
            height="400"
            placeholder="请输入文章内容"
          />
        </el-form-item>
        <el-form-item
          label="封面"
          prop="resource"
        >
          <el-radio-group v-model="article.type">
            <el-radio :label="1">单图</el-radio>
            <el-radio :label="3">三图</el-radio>
            <el-radio :label="0">无图</el-radio>
            <!-- <el-radio :label="-1">自动</el-radio> -->
          </el-radio-group>
          <!-- 需要把选择的封面图片的地址放到article.cover.iamges里 -->
          <!-- 当你给事件处理函数传递了自定义参数以后，就无法得到原本的数据参数了 -->
          <!-- 如果想要在事件处理函数自定义传参以后还想得到原来的那个事件本身的参数，则手动指定$event,它就代表那个事件本身的参数 -->

          <template v-if="article.type>0">
            <div class="imageses">
              <upload-cover
                :key="index"
                v-for="(cover,index) in article.type"
                v-model=" article.image[index]"
              />
            </div>
            <!-- <upload-cover :key="index"
                          v-for="(cover,index) in article.cover.type"
                          @updata-cover="onUpdataCover(index,$event)"
                          :cover-image="article.cover.images[index]" />
                          当你给子组件提供数据既要使用还要修改 ，这时候可以用v-model来简化数据绑定 -->
            <!-- v-model="article.cover.images[index]"相当于以下
                          给子组件传递了一个名字叫value的数据
                          :value="article.cover.images[index]"
                          默认监听input事件，当事件发生，它会让绑定数据=事件参数
                          @input="article.cover.images[index]=事件参数" -->
          </template>
        </el-form-item>
        <el-form-item
          label="频道"
          prop="region"
        >
          <el-select
            v-model="article.channel_id"
            placeholder="请选择频道"
          >
            <el-option
              :label="item.name"
              v-for="(item,index) in channels"
              :key="index"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <!-- <el-button type="primary"
                     @click="onPublish(false)">{{$route.query.id?'修改文章':'发布文章'}}</el-button>
          <el-button @click="onPublish(true)">存入草稿</el-button> -->
          <el-button
            type="primary"
            @click="onPublish(false)"
          >发布文章</el-button>
          <el-button @click="onPublish(true)">存入草稿</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { channel } from '@/api/channel'
import { publishArticle, getAppointArticle, updataArticle } from '@/api/article'
import { uploadImages } from '@/api/images'
import UploadCover from './components/upload-cover'
import { APP_CONFIG } from '@/config'
import readFileImg from '@/utils/image-compress' // 图片压缩
// import { ElementTiptap } from 'element-tiptap'
import {
  // 需要的 extensions
  Doc,
  Text,
  Paragraph,
  Heading,
  Bold,
  Underline,
  Italic,
  Strike,
  ListItem,
  BulletList,
  OrderedList,
  Image,
  ElementTiptap
} from 'element-tiptap'
export default {
  name: 'Publish',
  components: {
    'el-tiptap': ElementTiptap,
    'upload-cover': UploadCover
  },
  props: {},
  data () {
    return {
      baseURL: this.baseURL,
      article: {
        title: '',
        content: '',
        type: 1,
        image: [],
        channel_id: null
      },
      channels: [],
      rules: {
        title: [
          { required: true, message: '标题必填', trigger: 'change' }
        ],
        content: [
          { required: true, message: '内容不能为空', trigger: 'change' }
        ]
      },
      extensions: [
        new Doc(),
        new Text(),
        new Paragraph(),
        new Heading({ level: 5 }),
        new Bold({ bubble: true }), // 在气泡菜单中渲染菜单按钮
        new Underline({ bubble: true, menubar: false }), // 在气泡菜单而不在菜单栏中渲染菜单按钮
        new Italic(),
        new Strike(),
        new ListItem(),
        new BulletList(),
        new OrderedList(),
        new Image({
          // 默认生成base64，字符串和内容储存在一起，如果需要自定义图片上传需要以下api：uploadRequest
          async uploadRequest (file) {
            const fd = await new Promise((resolve, reject) => {
              readFileImg(file, resolve, reject)
            })
            // const fd = new FormData() // 创建文件类型数据
            // fd.append('image', file)
            return uploadImages(fd).then(res => {
              return `${APP_CONFIG.STATIC_HOST}/uploads/${res.data.data.url}`
            })
          } // 图片上传方法，返回一个Promise<url>
        })
      ]
    }
  },
  computed: {},
  watch: {},
  created () {
    this.loadChannel()
    if (this.$route.query.id) {
      this.loadArticle(this.$route.query.id)
    }
  },
  mounted () { },
  methods: {
    loadChannel () {
      channel().then(res => {
        this.channels = res.data.data
      })
    },
    async onPublish (draft = false) {
      // 如果是修改文章则是需要传文章id，否则是新增文章
      const articleId = this.$route.query.id
      if (articleId) {
        this.article.image = this.article.image.toString()
        await updataArticle(articleId, this.article, draft)
        this.$message({
          type: 'success',
          message: `${draft ? '存入草稿' : '发布'}成功`
        })
        this.$router.push('/article')
      } else {
        this.article.image = this.article.image.toString()
        await publishArticle(this.article, draft)
        this.$message({
          type: 'success',
          message: `${draft ? '存入草稿' : '发布'}成功`
        })
        this.$router.push('/article')
      }
    },
    async loadArticle (id) {
      const res = await getAppointArticle(id)
      this.article = res.data.data
      this.article.type = Number(res.data.data.type)
      this.article.image && (this.article.image = this.article.image.split(','))
      this.article.image || (this.article.image = [])
    },
    onUpdataCover (index, url) {
      this.article.cover.images[index] = url
    }
  }
}
</script>

<style lang='less' scoped>
.imageses {
  display: flex;
  flex-direction: row;
}
</style>
